package com.example.fw;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactData;

public class ContactHelper extends HelperBase
{

	public ContactHelper(ApplicationManager manager)
	{
		super(manager);
	}

	public void fillContactForm(ContactData contact)
	{
		type(By.name("firstname"), contact.firstName);
		type(By.name("lastname"), contact.lastName);
		type(By.name("address"), contact.address);
		type(By.name("home"), contact.homePhone);
		type(By.name("mobile"), contact.mobilePhone);
		type(By.name("work"), contact.workPhone);
		type(By.name("email"), contact.email1);
		type(By.name("email2"), contact.email2);
		selectByText(By.name("bday"), contact.birthDay);
		selectByText(By.name("bmonth"), contact.birthMonth);	
		type(By.name("byear"), contact.birthYear);
		selectByText(By.name("new_group"), contact.group);
		type(By.name("address"), contact.address2);
		type(By.name("phone2"), contact.phone2);
	}
	
	public void fillContactModificationForm(ContactData contact)
	{
		type(By.name("firstname"), contact.firstName);
		type(By.name("lastname"), contact.lastName);
		type(By.name("address"), contact.address);
		type(By.name("home"), contact.homePhone);
		type(By.name("mobile"), contact.mobilePhone);
		type(By.name("work"), contact.workPhone);
		type(By.name("email"), contact.email1);
		type(By.name("email2"), contact.email2);
		selectByText(By.name("bday"), contact.birthDay);
		selectByText(By.name("bmonth"), contact.birthMonth);	
		type(By.name("byear"), contact.birthYear);
		type(By.name("address"), contact.address2);
		type(By.name("phone2"), contact.phone2);
	}

	public void submitCreation()
	{
		click(By.name("submit"));
	}

	public void editContactByIndex(int index)
	{
		click(By.xpath("(//img[@alt='Edit'])[" + index + "]"));
		
	}

	public void deleteContact()
	{
		click(By.xpath("(//input[@name='update'])[2]"));
	}

	public void submitGroupModification()
	{
		click(By.xpath("(//input[@name='update'])[1]"));
	}

	public List<ContactData> getContacts()
	{
		List<ContactData> contacts = new ArrayList<ContactData>();
		List<WebElement> rows = driver.findElements(By.xpath("//table/tbody/tr[@name = 'entry']"));
		for (WebElement row : rows)
		{	
			ContactData contact = new ContactData();
			List<WebElement> cells = row.findElements(By.tagName("td"));
			
			String fname = cells.get(2).getText();
			String lname = cells.get(3).getText();
			
			contact.firstName = fname;
			contact.lastName = lname;
			contacts.add(contact);
		}
		return contacts;
	}
}